﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Security.Principal;
using System.Linq;

namespace AuthDemo.Converters
{
    public class UserStatusConverter : IValueConverter
    {
        bool requireRole = false;
        string roleString = null;

        public bool RequireRole
        {
            get { return requireRole; }
            set { requireRole = value; }
        }

        public string Roles
        {
            get { return roleString; }
            set { roleString = value; }
        }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool result = false;

            IPrincipal user = value as IPrincipal;

            if (user == null)
            {
                return false;
            }
            else
            {
                result = user.Identity.IsAuthenticated;

                if (requireRole  == true && roleString != null)
                {
                    bool hasRequiredRole = false;

                    var rolesList = roleString.Split(' ').ToList();

                    foreach (var rl in rolesList)
                    {
                        if (user.IsInRole(rl))
                        {
                            hasRequiredRole = true;
                            break;
                        }
                    }

                    result = result && hasRequiredRole;
                }
            }

            return (result ? Visibility.Visible : Visibility.Collapsed);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
